package com.anrongtec.zcpt.tab04;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.authentication.AuthorizeReceiver;
import com.anrongtec.zcpt.authentication.BillOperation;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.callback.StoreStringCallBack;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.logo.LoginActivity;
import com.anrongtec.zcpt.manager.CheckNewVersionManager;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.Util;
import com.art.base.util.AppManager;
import com.art.base.util.DialogUtil;
import com.art.base.util.FileSizeUtil;
import com.art.base.util.PreferenceUtils;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 设置页面
 *
 * @author chenjiaotuo
 */
@SuppressLint("NewApi")
public class SettingActivity extends BaseActivity implements View.OnClickListener {
	private PopupWindow popupWindow;

	private TextView tv_setting_clean_update_record, tv_setting_cache_size, tv_setting_suggestion_feedback,
			tv_setting_version_name;
	private AppCompatButton btn_logout;
	private LinearLayoutCompat ll_setting_app_version;
	private LinearLayout ll_setting_clean_cache;
	private ImageView iv_setting_keep_new_version;
	private ProgressDialog proDialog;
	private AppCompatButton btn_cancel;

	//信达注销
	public static final String CONTENT_URI = "content://com.xdja.app.pj";
	/**
	 * 返回代码
	 */
	public static final String RESULT_CODE = "resultCode";
	/**
	 * 返回信息
	 */
	public static final String RESULT_MESSAGE = "message";
	/**
	 * 票据信息
	 */
	public static final String BILLSTR = "billStr";
	private static String code;
	private static String message;
	private Context context;
	private AuthorizeReceiver loginOutReceviver;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);
		initViews();
		initEvents();
		initData();

//		loginOutReceviver = new AuthorizeReceiver();
//		registerReceiver(loginOutReceviver,filter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
//		unregisterReceiver(loginOutReceviver);
	}


	@Override
	protected void onCreateCustomToolBar(Toolbar toolbar) {
		super.onCreateCustomToolBar(toolbar);
		toolbar.setTitle("设置");
	}

	@Override
	protected void initViews() {
		tv_setting_clean_update_record = (TextView) findViewById(R.id.tv_setting_clean_update_record);
		ll_setting_clean_cache = (LinearLayout) findViewById(R.id.ll_setting_clean_cache);
		tv_setting_cache_size = (TextView) findViewById(R.id.tv_setting_cache_size);
		tv_setting_cache_size.setText(FileSizeUtil.getAutoFileOrFilesSize(ImageLoader.getInstance().getDiskCache().getDirectory().getAbsolutePath()));
		tv_setting_suggestion_feedback = (TextView) findViewById(R.id.tv_setting_suggestion_feedback);
		tv_setting_version_name = (TextView) findViewById(R.id.tv_setting_version_name);
		ll_setting_app_version = (LinearLayoutCompat) findViewById(R.id.ll_setting_app_version);
		iv_setting_keep_new_version = (ImageView) findViewById(R.id.iv_setting_keep_new_version);
		btn_logout = (AppCompatButton) findViewById(R.id.btn_setting_logout);
		btn_cancel = (AppCompatButton) findViewById(R.id.btn_cancel);
	}

	@Override
	protected void initEvents() {
		tv_setting_clean_update_record.setOnClickListener(this);
		ll_setting_clean_cache.setOnClickListener(this);
		tv_setting_suggestion_feedback.setOnClickListener(this);
		iv_setting_keep_new_version.setOnClickListener(this);
		ll_setting_app_version.setOnClickListener(this);
		btn_logout.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);
	}

	@Override
	protected void initData() {
		tv_setting_version_name.setText("当前版本号： " + Util.getVersionName(this));
		if (PreferenceUtils.getInstance(this).getBoolean(Constant.SETTING_KEEP_NEW_VERSION)) {
			iv_setting_keep_new_version.setImageResource(R.drawable.open_icon);
		} else {
			iv_setting_keep_new_version.setImageResource(R.drawable.close_icon);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.tv_setting_clean_update_record:
				// 清除升级记录
				setCleanUpdateRecord();
				break;
			case R.id.ll_setting_clean_cache:
				// 清空缓存
				setCleanCache();
				break;
			case R.id.tv_setting_suggestion_feedback:
				// 意见反馈
				intent = new Intent(this, SuggestionFeedbackActivity.class);
				startActivity(intent);
				break;
			case R.id.ll_setting_app_version:
				// 检查更新信息，并且弹吐司
				CheckNewVersionManager.getInstance().checkVersion(SettingActivity.this, true);
				break;
			case R.id.iv_setting_keep_new_version:
				// 与新版本保持同步，自动更新
				// 偏好设置存储信息，是否同步更新
				if (PreferenceUtils.getInstance(this).getBoolean(Constant.SETTING_KEEP_NEW_VERSION)) {
					iv_setting_keep_new_version.setImageResource(R.drawable.close_icon);
					PreferenceUtils.getInstance(this).save(Constant.SETTING_KEEP_NEW_VERSION, false);
				} else {
					iv_setting_keep_new_version.setImageResource(R.drawable.open_icon);
					PreferenceUtils.getInstance(this).save(Constant.SETTING_KEEP_NEW_VERSION, true);
				}
				break;

			case R.id.btn_setting_logout:
				logout();
				break;
			case R.id.btn_cancel:
				BillOperation.deleteAuthorizeBill(this);
				Intent intent = new Intent();
				intent.putExtra("packageName","com.anrongtec.zcpt");
				intent.setAction("com.xdja.unifyauthorize.ACTION_LOGOUT");
				sendBroadcast(intent);
				break;
			default:
				break;
		}

	}


	/**
	 * 退出登录
	 */
	private void logout() {
		DialogUtil.createAlertDialog(this, "退出登录", 0, "是否退出应用商店？", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				proDialog = DialogUtil.createLoadingDialog(SettingActivity.this, "正在注销登录...");
				proDialog.show();
				String json = GsonUtil.toLogoutJson();
				HttpUtil.post(json, new StoreStringCallBack(SettingActivity.this) {
					@Override
					public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
						super.onResponse(arg0, arg1, arg2, arg3);
						JsonDataRestult<Object> result = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<Object>>() {
						}.getType());
						if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {

							//退出 change by lina
							if (proDialog != null) {
								proDialog.dismiss();
							}
							AppManager.getAppManager().finishAllActivity();

							startActivity(new Intent(SettingActivity.this, LoginActivity.class));

						}
					}

					@Override
					public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
						super.onError(isFromCache, call, response, e);
					}
				});

				//TODO 上报登出
//				String accountId = PreferenceUtils.getInstance(SettingActivity.this).getString(PreferenceKey.ACCOUNT_ID);
//				WLData.getInstance().reportLogout(accountId, Events.LOGOUT);

//				退出到登录页面
//				Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
//				ComponentName cn = intent.getComponent();
//				Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
//				startActivity(mainIntent);


				//解绑统一认证服务
//				UAManager.getInstance().unbindService();

				//完全退出
//				android.os.Process.killProcess(android.os.Process.myPid()); 
//				System.exit(1);
				/*统一认证 管理 注视By lina  因为下面这个是广西auth认证*/
				/*if(UAManager.getInstance()!=null) {
					UAManager.getInstance().authLogout("");
     			}
				intent = new Intent(Constant.Action.EXIT);
				sendBroadcast(intent);
				finish();*/

			}
		});
	}

	/**
	 * 清除升级记录点击事件
	 */
	private void setCleanUpdateRecord() {
//		OnClickListener onCleanListener = new View.OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//			}
//		};
//		setPopupWindowShow(SettingActivity.this, "清除升级记录？", onCleanListener);

		DialogUtil.createAlertDialog(this, "清除升级记录", 0, "是否清除升级记录？", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//TODO 清除升级记录

			}
		});

	}

	/**
	 * 清空缓存点击事件
	 */
	private void setCleanCache() {
//		OnClickListener onCleanListener = new View.OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//			}
//		};
//		setPopupWindowShow(SettingActivity.this, "清除商店缓存？", onCleanListener);

		DialogUtil.createAlertDialog(this, "清除缓存", 0, "是否清除缓存？", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//TODO 清除缓存
				ImageLoader.getInstance().getDiskCache().clear();
				tv_setting_cache_size.setText(FileSizeUtil.getAutoFileOrFilesSize(ImageLoader.getInstance().getDiskCache().getDirectory().getAbsolutePath()));
			}
		});


	}

	/**
	 * 设置屏幕的背景透明度
	 *
	 * @param bgAlpha
	 */
	private void setBackgroundAlpha(float bgAlpha) {
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = bgAlpha; // 0.0-1.0
		getWindow().setAttributes(lp);
	}


	/**
	 * 显示提示popupWindow
	 *
	 * @param context
	 * @param content
	 *            提示内容
	 * @param onOkClick
	 *            确定按钮点击事件
	 */
//	@SuppressLint("InflateParams")
//	private void setPopupWindowShow(Context context, String content, OnClickListener onOkClick) {
//		
//		View contentView = LayoutInflater.from(context).inflate(R.layout.item_setting_popwindow, null);
//		popupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
//		TextView tvContent = (TextView) contentView.findViewById(R.id.item_setting_popwindow_content);
//		tvContent.setText(content);
//		AppCompatButton acb_setting_popwindow_cancel = (AppCompatButton) contentView
//				.findViewById(R.id.acb_setting_popwindow_cancel);
//		AppCompatButton acb_setting_popwindow_confirm = (AppCompatButton) contentView
//				.findViewById(R.id.acb_setting_popwindow_confirm);
//		acb_setting_popwindow_confirm.setOnClickListener(onOkClick);
//		acb_setting_popwindow_cancel.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				popupWindow.dismiss();
//				popupWindow = null;
//			}
//		});
//		popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//
//			@Override
//			public void onDismiss() {
//				// popupWindow消失时候页面背景恢复
//				setBackgroundAlpha(1f);
//			}
//		});
//		// 页面背景变暗
//		setBackgroundAlpha(0.5f);
//		popupWindow.showAtLocation(SettingActivity.this.findViewById(R.id.ll_setting), Gravity.BOTTOM, 0, 0);
//	}







}
